package org.jeecg.modules.carinfo.controller;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.DySmsEnum;
import org.jeecg.common.util.DySmsHelper;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.carData.entity.CarData;
import org.jeecg.modules.carData.service.ICarDataService;
import org.jeecg.modules.carinfo.entity.CarRegister;
import org.jeecg.modules.carinfo.service.ICarRegisterService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.carinfo.util.OCR;
import org.jeecg.modules.carinfo.util.QueryEnv;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.enterpriseBasicInformation.entity.EnterpriseBasicInformation;
import org.jeecg.modules.enterpriseBasicInformation.service.IEnterpriseBasicInformationService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import net.coobird.thumbnailator.Thumbnails;

/**
 * @Description: 车辆登记
 * @Author: jeecg-boot
 * @Date: 2023-11-28
 * @Version: V1.0
 */
@Api(tags = "车辆登记")
@RestController
@RequestMapping("/carinfo/carRegister")
@Slf4j
public class CarRegisterController extends JeecgController<CarRegister, ICarRegisterService> {
    @Autowired
    private ICarRegisterService carRegisterService;
    @Autowired
    private IEnterpriseBasicInformationService enterpriseBasicInformationService;
    @Autowired
    private ISysDepartService sysDepartService;


    /**
     * 分页列表查询
     *
     * @param carRegister
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "车辆登记-分页列表查询")
    @ApiOperation(value = "车辆登记-分页列表查询", notes = "车辆登记-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CarRegister carRegister,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        //EnterpriseBasicInformation enterprise = enterpriseBasicInformationService.list().get(0);
        carRegister.setPlateNo("*" + carRegister.getPlateNo() + "*");
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username=loginUser.getUsername();
        if(!username.equals("admin")){
            List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
            List<String> departNames = sysDeparts.stream()
                    .filter(item -> item.getOrgType().equals("1"))
                    .map(SysDepart::getDepartName)
                    .collect(Collectors.toList());
            if(departNames==null||departNames.size()==0){
                return Result.error("未找到公司信息，请联系管理员");
            }
            queryWrapper.eq("locatin", departNames.get(0));
        }

        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param carRegister
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "车辆登记-分页列表查询")
    @ApiOperation(value = "车辆登记-分页列表查询--对外", notes = "车辆登记-分页列表查询")
    @GetMapping(value = "/m/list")
    public Result<?> queryPageListM(CarRegister carRegister,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    @RequestParam(name = "locatin") String locatin,
                                    HttpServletRequest req) {
        //EnterpriseBasicInformation enterprise = enterpriseBasicInformationService.list().get(0);
        carRegister.setPlateNo("*" + carRegister.getPlateNo() + "*");
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());

       /* LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username=loginUser.getUsername();
        if(!username.equals("admin")){
            List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
            List<String> departNames = sysDeparts.stream()
                    .filter(item -> item.getOrgType().equals("1"))
                    .map(SysDepart::getDepartName)
                    .collect(Collectors.toList());
            if(departNames==null||departNames.size()==0){
                return Result.error("未找到公司信息，请联系管理员");
            }
            queryWrapper.eq("locatin", departNames.get(0));
        }
*/
        queryWrapper.eq("locatin", locatin);
        queryWrapper.orderByDesc("create_time");
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param carRegister
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "车辆登记-分页列表查询")
    @ApiOperation(value = "车辆登记-分页列表查询", notes = "车辆登记-分页列表查询")
    @GetMapping(value = "/examineList")
    public Result<?> examineList(CarRegister carRegister,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {
        //EnterpriseBasicInformation enterprise = enterpriseBasicInformationService.list().get(0);
        carRegister.setStatus(0);
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username=loginUser.getUsername();
        if(!username.equals("admin")){
            List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
            List<String> departNames = sysDeparts.stream()
                    .filter(item -> item.getOrgType().equals("1"))
                    .map(SysDepart::getDepartName)
                    .collect(Collectors.toList());
            if(departNames==null||departNames.size()==0){
                return Result.error("未找到公司信息，请联系管理员");
            }
            queryWrapper.eq("locatin", departNames.get(0));
        }
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param carRegister
     * @return
     */
    @AutoLog(value = "车辆登记-添加")
    @ApiOperation(value = "车辆登记-添加", notes = "车辆登记-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CarRegister carRegister) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username=loginUser.getUsername();
        if(!username.equals("admin")){
            List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
            List<String> departNames = sysDeparts.stream()
                    .filter(item -> item.getOrgType().equals("1"))
                    .map(SysDepart::getDepartName)
                    .collect(Collectors.toList());
            if(departNames==null||departNames.size()==0){
                return Result.error("未找到公司信息，请联系管理员");
            }
            carRegister.setLocatin(departNames.get(0));
        }else {
            carRegister.setLocatin(username);
        }
        carRegisterService.save(carRegister);
        return Result.OK("添加成功！");
    }

    /**
     * 查询是否登记
     *
     * @param
     * @return
     */
    @AutoLog(value = "车辆登记-查询是否登记")
    @ApiOperation(value = "车辆登记-查询是否登记", notes = "车辆登记-查询是否登记")
    @GetMapping(value = "/m/exist")
    public Result<?> exist(@RequestParam(name = "plateNo", required = true) String plateNo,
                           @RequestParam(name = "locatin", required = true) String location,
                           @RequestParam(name = "pin", required = true) String pin)  {
//        EnterpriseBasicInformation enterprise = enterpriseBasicInformationService.list().get(0);
//        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        String username = loginUser.getRealname();
        LambdaQueryWrapper<CarRegister> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CarRegister::getLocatin, location);
        if(!plateNo.equals("")){
            lambdaQueryWrapper.eq(CarRegister::getPlateNo, plateNo);
        }else{
            lambdaQueryWrapper.eq(CarRegister::getPin, pin);
        }
        //lambdaQueryWrapper.eq(CarRegister::getPlateNo, plateNo);
        if (carRegisterService.list(lambdaQueryWrapper).size() == 0) {
            return Result.error("未登记！");
        }
        //throw new Exception("车辆登记信息"+carRegisterService.list(lambdaQueryWrapper));
        log.error("车辆登记信息"+carRegisterService.list(lambdaQueryWrapper).size());
        return Result.OK("已登记！");
    }

    /**
     * 查询是否登记
     *
     * @param
     * @return
     */
    @AutoLog(value = "车辆登记-查询是否登记")
    @ApiOperation(value = "车辆登记-查询是否登记", notes = "车辆登记-查询是否登记")
    @GetMapping(value = "/m/exist2")
    public Result<?> exist2(@RequestParam(name = "pin", required = true) String pin,
                           @RequestParam(name = "locatin", required = true) String location) {
//        EnterpriseBasicInformation enterprise = enterpriseBasicInformationService.list().get(0);
//        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        String username = loginUser.getRealname();
        LambdaQueryWrapper<CarRegister> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CarRegister::getLocatin, location);
        lambdaQueryWrapper.eq(CarRegister::getPin, pin);
        if (carRegisterService.list(lambdaQueryWrapper).size() == 0) {
            return Result.error("未登记！");
        }
        return Result.OK("已登记！");
    }
    @Autowired
    QueryEnv queryEnv;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private ICarDataService carDataService;

    /**
     * 添加
     *
     * @param carRegister
     * @return
     */
    @AutoLog(value = "车辆登记-添加")
    @ApiOperation(value = "车辆登记-添加", notes = "车辆登记-添加")
    @PostMapping(value = "/m/add")
    public Result<?> mAdd(@RequestBody CarRegister carRegister) {
        if (!carRegister.getCarSort().equals(0)){ //非进出厂车辆
            //内部车辆，直接通过
            LambdaQueryWrapper<CarData> lqw = Wrappers.lambdaQuery(CarData.class);
            lqw.eq(CarData::getPlateNo, carRegister.getPlateNo());
            List<CarData> list = carDataService.list(lqw);
            if (list!=null && list.size()>0){
                carRegister.setStatus(1);//登记状态：已通过
            }else {
                carRegister.setStatus(0);//登记状态：未审核
            }
            carRegister.setStatusLedger(1);//线下台账状态：是
        }else { //进出厂车辆
            boolean flag = getEnv(carRegister);
            if (flag) {
                carRegister.setStatus(1);//登记状态：已通过
                // 登记信息核对OK，添加进出厂车辆信息
                CarData carData = new CarData();
                BeanUtils.copyProperties(carRegister,carData);
                carData.setCompanyName(carRegister.getLocatin());
                carDataService.save(carData);
            }
        }
        carRegister.setFuelType(sysDictService.queryDictTextByValue("fuel_type", carRegister.getFuelType()));
        carRegisterService.save(carRegister);
        return Result.OK("添加成功！");
    }

    private boolean getEnv(CarRegister carRegister) {
        //新能源车辆，直接通过
        if (carRegister.getPlateColor().equals("绿色")){
            return true;
        }
        int local = queryEnv.getLocal(carRegister.getPlateNo());
        if (local == 1) {
            return true;
        } else if (local == -1) {
            return false;
        }
        int zhongjiao = queryEnv.getZhongJiao(carRegister.getPlateNo(), carRegister.getPlateColor(), carRegister.getLocatin());
        if (zhongjiao == 1) {
            return true;
        } else if (zhongjiao == -1) {
            return false;
        }
        boolean angmei = queryEnv.getAngMei(carRegister.getVin(), carRegister.getPlateNo(), carRegister.getPlateColor(), carRegister.getLocatin());
        if (angmei) {
            return true;
        }

        return false;
    }

    @AutoLog(value = "检查手机号是否存在")
    @ApiOperation(value = "车辆登记-检查手机号是否存在", notes = "车辆登记-检查手机号是否存在")
    @GetMapping(value = "/m/existPhone")
    public Result<?> existPhone(@RequestParam(name = "phoneNum", required = true) String phoneNum) {
        EnterpriseBasicInformation enterprise = enterpriseBasicInformationService.list().get(0);
       /* LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = loginUser.getRealname();*/
        LambdaQueryWrapper<CarRegister> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CarRegister::getPhoneNum, phoneNum);
        lambdaQueryWrapper.eq(CarRegister::getLocatin, enterprise.getEnterpriseName());
        if (carRegisterService.list(lambdaQueryWrapper).size() == 0) {
            return Result.OK("验证成功！");
        }
        return Result.error("验证失败！");
    }

    /**
     * 编辑
     *
     * @param carRegister
     * @return
     */
    @AutoLog(value = "车辆登记-编辑")
    @ApiOperation(value = "车辆登记-编辑", notes = "车辆登记-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CarRegister carRegister) {
        carRegisterService.updateById(carRegister);
        return Result.OK("编辑成功!");
    }

    /**
     * 编辑登记状态
     *
     * @param carRegister
     * @return
     */
    @AutoLog(value = "车辆登记-编辑登记状态")
    @ApiOperation(value = "车辆登记-编辑登记状态--对外", notes = "车辆登记-编辑登记状态")
    @PostMapping(value = "/m/editStatusLedger")
    public Result<?> editStatusLedger(@RequestBody CarRegister carRegister) {
        LambdaUpdateWrapper<CarRegister> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        if (!carRegister.getCarSort().equals(0)){
            boolean flag = getEnv(carRegister);
            if (flag) {
                lambdaUpdateWrapper.set(CarRegister::getStatus, 1);
            }
        }
        lambdaUpdateWrapper.set(CarRegister::getStatusLedger, carRegister.getStatusLedger());
        lambdaUpdateWrapper.eq(CarRegister::getId, carRegister.getId());
        carRegisterService.update(lambdaUpdateWrapper);
        return Result.OK("编辑成功!");
    }

    /**
     * 更新状态
     *
     * @param carRegister
     * @return
     */
    @AutoLog(value = "车辆登记-更新状态")
    @ApiOperation(value = "车辆登记-更新状态", notes = "车辆登记-更新状态")
    @PutMapping(value = "/editStatus/{flag}")
    public Result<?> editStatus(@RequestBody CarRegister carRegister,
                                @PathVariable("flag") Integer flag) throws ClientException {
        LambdaUpdateWrapper<CarRegister> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        if(flag==0) {
            lambdaUpdateWrapper.set(CarRegister::getStatus, 1);
        }
        if(flag==1) {
            lambdaUpdateWrapper.set(CarRegister::getStatus, -1);
        }
        lambdaUpdateWrapper.eq(CarRegister::getId, carRegister.getId());
        carRegisterService.update(lambdaUpdateWrapper);
        CarRegister byId = carRegisterService.getById(carRegister.getId());
        // 登记信息核对OK，添加进出厂车辆信息
        CarData carData = new CarData();
        BeanUtils.copyProperties(byId, carData);
        carData.setCompanyName(byId.getLocatin());
        carDataService.save(carData);
        //给申请人发送短信提示审批通过
        /*DySmsEnum approveTemplateCode = DySmsEnum.APPROVE_TEMPLATE_CODE;
        JSONObject object = new JSONObject();
        object.put("name", carRegister.getDriverName());
        object.put("count", 1);
        object.put("type", "车辆登记");
        boolean result = DySmsHelper.sendSms(carRegister.getPhoneNum(), object, approveTemplateCode);*/
        return Result.OK("编辑成功!");
    }

    /**
     * 更新状态
     *
     * @param carRegister
     * @return
     */
    @AutoLog(value = "车辆登记-更新状态")
    @ApiOperation(value = "车辆登记-更新状态--对外", notes = "车辆登记-更新状态--对外--只传id就可以")
    @PutMapping(value = "/m/editStatus")
    public Result<?> editStatusM(@RequestBody CarRegister carRegister) throws ClientException {
        LambdaUpdateWrapper<CarRegister> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(CarRegister::getStatus, 1);
        lambdaUpdateWrapper.eq(CarRegister::getId, carRegister.getId());
        carRegisterService.update(lambdaUpdateWrapper);
        //给申请人发送短信提示审批通过
        /*DySmsEnum approveTemplateCode = DySmsEnum.APPROVE_TEMPLATE_CODE;
        JSONObject object = new JSONObject();
        object.put("name", carRegister.getDriverName());
        object.put("count", 1);
        object.put("type", "车辆登记");
        boolean result = DySmsHelper.sendSms(carRegister.getPhoneNum(), object, approveTemplateCode);*/
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车辆登记-通过id删除")
    @ApiOperation(value = "车辆登记-通过id删除", notes = "车辆登记-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        carRegisterService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "车辆登记-批量删除")
    @ApiOperation(value = "车辆登记-批量删除", notes = "车辆登记-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.carRegisterService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车辆登记-通过id查询")
    @ApiOperation(value = "车辆登记-通过id查询", notes = "车辆登记-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CarRegister carRegister = carRegisterService.getById(id);
        if (carRegister == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(carRegister);
    }

    /**
     * 通过id查询
     *
     * @param
     * @return
     */
    @AutoLog(value = "车辆登记-分类统计")
    @ApiOperation(value = "车辆登记-分类统计", notes = "车辆登记-分类统计")
    @GetMapping(value = "/queryByCount")
    public Result<?> queryByCount() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username=loginUser.getUsername();
            List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
            List<String> departNames = sysDeparts.stream()
                    .filter(item -> item.getOrgType().equals("1"))
                    .map(SysDepart::getDepartName)
                    .collect(Collectors.toList());
            if(departNames==null||departNames.size()==0){
                return Result.error("未找到公司信息，请联系管理员");
            }
        //EnterpriseBasicInformation enterprise = enterpriseBasicInformationService.list().get(0);
        QueryWrapper<CarRegister> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("locatin", departNames.get(0));
        queryWrapper.select("max(create_time) as create_time");
        Date max = carRegisterService.getOne(queryWrapper).getCreateTime();
        QueryWrapper<CarRegister> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("locatin", departNames.get(0));
        queryWrapper1.select("min(create_time) as create_time");
        Date min = carRegisterService.getOne(queryWrapper1).getCreateTime();
        long l = (max.getTime() - min.getTime()) / (3600 * 24 * 1000) + 1;
        QueryWrapper<CarRegister> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("locatin", departNames.get(0));
        queryWrapper2.select("count(1) as count");
        Map<String, Object> map = carRegisterService.getMap(queryWrapper2);
        long total = Long.valueOf(map.get("count").toString());
        long average = total / l;
        // 设置返回值
        List<Map<String, String>> list = carRegisterService.getCount(departNames.get(0));
        List<Map<String, String>> updatedList = new ArrayList<>();
        for (Map<String, String> mapString : list) {
            Map<String, String> updatedMap = new HashMap<>();
            String name = mapString.get("name");
            if ("0".equals(name)) {
                updatedMap.put("name", "国零");
                updatedMap.put("value", mapString.get("value"));
            } else if ("1".equals(name)) {
                updatedMap.put("name", "国一");
                updatedMap.put("value", mapString.get("value"));

            } else if ("2".equals(name)) {
                updatedMap.put("name", "国二");
                updatedMap.put("value", mapString.get("value"));

            } else if ("3".equals(name)) {
                updatedMap.put("name", "国三");
                updatedMap.put("value", mapString.get("value"));

            } else if ("4".equals(name)) {
                updatedMap.put("name", "国四");
                updatedMap.put("value", mapString.get("value"));

            } else if ("5".equals(name)) {
                updatedMap.put("name", "国五");
                updatedMap.put("value", mapString.get("value"));

            } else if ("6".equals(name)) {
                updatedMap.put("name", "国六");
                updatedMap.put("value", mapString.get("value"));

            } else if ("D".equals(name)) {
                updatedMap.put("name", "新能源");
                updatedMap.put("value", mapString.get("value"));

            } else {
                updatedMap.put("name", "排放标准未知");
                updatedMap.put("value", mapString.get("value"));
            }
            updatedList.add(updatedMap);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", updatedList);
        jsonObject.put("total", total);
        jsonObject.put("average", average);
        return Result.OK(jsonObject);
    }

    @Autowired
    OCR ocr;
    @Value(value="${jeecg.uploadType}")
    private String uploadType;

    /**
     * 文件上传统一方法
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/upload")
    public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
        Result<?> result = new Result<>();
        String savePath = "";
        String bizPath = DateUtil.formatDate(new Date());
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        String plateNo = request.getParameter("plateNo");
        String vin = request.getParameter("vin");
        String name = request.getParameter("name");
        Long start = System.currentTimeMillis();
        if (name.equals("1")) {
            try {
                ;
                JSONObject jsonObject = ocr.getVin(saveFileWithoutWaterMark(file));
                Long end = System.currentTimeMillis();
                System.err.println(vin + (end - start));
                if (jsonObject.getString("plate").equals(plateNo) && jsonObject.getString("vin").equals(vin)) {
                } else {
                    return Result.error("错误");
                }
            } catch (Exception e) {
                Long end = System.currentTimeMillis();
                System.err.println(vin + (end - start));
                return Result.error("错误");
            }
        }

//        savePath = this.uploadLocal(file, bizPath);
        savePath = CommonUtils.upload(file, bizPath, uploadType);
        if (oConvertUtils.isNotEmpty(savePath)) {
            result.setMessage(savePath);
            result.setSuccess(true);
        } else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        return result;
    }

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    /**
     * 本地文件上传
     *
     * @param mf      文件
     * @param bizPath 自定义路径
     * @return
     */
    private String uploadLocal(MultipartFile mf, String bizPath) {
        try {
            mf = saveFileWithoutWaterMark(mf);
            String ctxPath = uploadpath;
            String fileName = null;
            File file = new File(ctxPath + File.separator + bizPath + File.separator);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            String orgName = mf.getOriginalFilename();// 获取文件名
            orgName = CommonUtils.getFileName(orgName);
            if (orgName.indexOf(".") != -1) {
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
            } else {
                fileName = orgName + "_" + System.currentTimeMillis();
            }
            String savePath = file.getPath() + File.separator + fileName;
            File savefile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), savefile);
            String dbpath = null;
            if (oConvertUtils.isNotEmpty(bizPath)) {
                dbpath = bizPath + File.separator + fileName;
            } else {
                dbpath = fileName;
            }
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            return dbpath;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }

    public MultipartFile saveFileWithoutWaterMark(MultipartFile file) {
        try {
            if ((1024 * 1024 * 0.1) <= file.getSize()) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                //小于 1M 的
                if ((1024 * 1024 * 0.1) <= file.getSize() && file.getSize() <= (1024 * 1024)) {
                    Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.9f).toOutputStream(outputStream);
                }
                // 1 - 2M 的
                else if ((1024 * 1024) < file.getSize() && file.getSize() <= (1024 * 1024 * 2)) {
                    Thumbnails.of(file.getInputStream()).scale(0.8f).outputQuality(0.6f).toOutputStream(outputStream);
                }// 2M 以上的
                else if ((1024 * 1024 * 2) < file.getSize()) {
                    Thumbnails.of(file.getInputStream()).scale(0.5f).outputQuality(0.3f).toOutputStream(outputStream);
                }

                byte[] bytes = outputStream.toByteArray();
                InputStream inputStream = new ByteArrayInputStream(bytes);
                //Boolean b=ImageIO.write(ImageIO.read(inputStream),"jpg",new File("D:/111.jpg"));
                // 转换城新的 MultipartFile 对象
                MultipartFile mfileInfos = new MockMultipartFile(file.getOriginalFilename(), file.getOriginalFilename(), file.getContentType(), inputStream);
                System.out.println("源文件大小:" + file.getSize() + "压缩后的大小:" + mfileInfos.getSize());
                return mfileInfos;
            }
            return file;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 导出excel
     *
     * @param request
     * @param carRegister
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CarRegister carRegister) {
        return super.exportXls(request, carRegister, CarRegister.class, "车辆登记");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CarRegister.class);
    }


}
